package com.example.projectmanagement.service.study;

import com.example.projectmanagement.model.study.UserLessonProgress;
import com.example.projectmanagement.model.study.Lesson;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.repository.study.UserLessonProgressRepository;
import com.example.projectmanagement.repository.study.LessonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class StudyProgressService {

    @Autowired
    private UserLessonProgressRepository progressRepository;
    
    @Autowired
    private LessonRepository lessonRepository;

    /**
     * 记录用户开始学习课时
     */
    @Transactional
    public UserLessonProgress startLesson(User user, Long lessonId) {
        Lesson lesson = lessonRepository.findById(lessonId)
                .orElseThrow(() -> new RuntimeException("Lesson not found with id: " + lessonId));
        
        // 检查是否已存在进度记录
        Optional<UserLessonProgress> existingProgress = progressRepository.findByUserAndLesson(user, lesson);
        if (existingProgress.isPresent()) {
            UserLessonProgress progress = existingProgress.get();
            // 如果状态是未开始，则更新为学习中
            if ("NOT_STARTED".equals(progress.getStatus())) {
                progress.setStatus("IN_PROGRESS");
                progress.setStartTime(LocalDateTime.now());
                return progressRepository.save(progress);
            }
            return progress;
        }
        
        // 创建新的进度记录
        UserLessonProgress progress = new UserLessonProgress();
        progress.setUser(user);
        progress.setLesson(lesson);
        progress.setStatus("IN_PROGRESS");
        progress.setStartTime(LocalDateTime.now());
        progress.setLastAccessTime(LocalDateTime.now());
        progress.setTotalDuration(lesson.getEstimatedDuration() != null ? lesson.getEstimatedDuration() * 60 : 0); // 转换为秒
        
        return progressRepository.save(progress);
    }

    /**
     * 更新用户课时学习进度
     */
    @Transactional
    public UserLessonProgress updateLessonProgress(User user, Long lessonId, Integer viewedDuration) {
        Lesson lesson = lessonRepository.findById(lessonId)
                .orElseThrow(() -> new RuntimeException("Lesson not found with id: " + lessonId));
        
        UserLessonProgress progress = progressRepository.findByUserAndLesson(user, lesson)
                .orElseThrow(() -> new RuntimeException("Progress not found for user and lesson"));
        
        progress.setViewedDuration(viewedDuration);
        progress.setLastAccessTime(LocalDateTime.now());
        
        // 根据观看时长更新状态
        if (progress.getTotalDuration() != null && progress.getTotalDuration() > 0) {
            double percentage = (double) viewedDuration / progress.getTotalDuration();
            if (percentage >= 0.8) { // 观看80%以上认为已完成
                progress.setStatus("COMPLETED");
                if (progress.getCompletionTime() == null) {
                    progress.setCompletionTime(LocalDateTime.now());
                }
            } else if (progress.getStatus().equals("NOT_STARTED")) {
                progress.setStatus("IN_PROGRESS");
                if (progress.getStartTime() == null) {
                    progress.setStartTime(LocalDateTime.now());
                }
            }
        }
        
        return progressRepository.save(progress);
    }

    /**
     * 完成课时学习
     */
    @Transactional
    public UserLessonProgress completeLesson(User user, Long lessonId) {
        Lesson lesson = lessonRepository.findById(lessonId)
                .orElseThrow(() -> new RuntimeException("Lesson not found with id: " + lessonId));
        
        UserLessonProgress progress = progressRepository.findByUserAndLesson(user, lesson)
                .orElseThrow(() -> new RuntimeException("Progress not found for user and lesson"));
        
        progress.setStatus("COMPLETED");
        progress.setViewedDuration(progress.getTotalDuration() != null ? progress.getTotalDuration() : 0);
        progress.setCompletionTime(LocalDateTime.now());
        progress.setLastAccessTime(LocalDateTime.now());
        
        return progressRepository.save(progress);
    }

    /**
     * 获取用户课时学习进度
     */
    public Optional<UserLessonProgress> getLessonProgress(User user, Long lessonId) {
        Lesson lesson = lessonRepository.findById(lessonId)
                .orElseThrow(() -> new RuntimeException("Lesson not found with id: " + lessonId));
        
        return progressRepository.findByUserAndLesson(user, lesson);
    }

    /**
     * 获取用户课程的所有课时进度
     */
    public List<UserLessonProgress> getCourseProgress(User user, Long courseId) {
        return progressRepository.findByUserAndLesson_Module_Course_Id(user, courseId);
    }

    /**
     * 获取用户已完成的课程课时列表
     */
    public List<UserLessonProgress> getCompletedLessons(User user, Long courseId) {
        return progressRepository.findCompletedLessonsByUserAndCourse(user.getId(), courseId);
    }

    /**
     * 获取用户在课程中已完成的课时数量
     */
    public Integer getCompletedLessonsCount(User user, Long courseId) {
        return progressRepository.countCompletedLessonsByUserAndCourse(user.getId(), courseId);
    }
    
    /**
     * 获取课程总体进度信息
     */
    public Map<String, Object> getCourseOverallProgress(User user, Long courseId) {
        List<UserLessonProgress> allProgress = getCourseProgress(user, courseId);
        Integer completedCount = getCompletedLessonsCount(user, courseId);
        
        Map<String, Object> progressInfo = new HashMap<>();
        progressInfo.put("totalLessons", allProgress.size());
        progressInfo.put("completedLessons", completedCount != null ? completedCount : 0);
        progressInfo.put("lessonProgresses", allProgress);
        
        return progressInfo;
    }

    /**
     * 重置课时进度
     */
    @Transactional
    public void resetLessonProgress(User user, Long lessonId) {
        Lesson lesson = lessonRepository.findById(lessonId)
                .orElseThrow(() -> new RuntimeException("Lesson not found with id: " + lessonId));
        
        UserLessonProgress progress = progressRepository.findByUserAndLesson(user, lesson)
                .orElseThrow(() -> new RuntimeException("Progress not found for user and lesson"));
        
        progress.setStatus("NOT_STARTED");
        progress.setViewedDuration(0);
        progress.setStartTime(null);
        progress.setCompletionTime(null);
        progress.setLastAccessTime(LocalDateTime.now());
        
        progressRepository.save(progress);
    }
}